const db = uniCloud.database();
const uniID = require('uni-id-common');

exports.main = async (event, context) => {
    const uniIDIns = uniID.createInstance({ context });

    let body = event;
    if (event.body !== undefined) {
        try {
            body = JSON.parse(event.body);
        } catch (e) {
            return { success: false, message: "请求体格式错误" };
        }
    }

    if (!body.uniIdToken) {
        return { success: false, message: "缺少身份令牌" };
    }

    const tokenRes = await uniIDIns.checkToken(body.uniIdToken);
    if (!tokenRes.uid) {
        return { success: false, message: "身份验证失败" };
    }
    const uid = tokenRes.uid;

    const { day, freeSlot } = body;
    if (!day || !freeSlot) {
        return { success: false, message: "缺少必要参数" };
    }
	// 3. 日期格式校验
	const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
	if (!dateRegex.test(day)) {
	  return {
	    code: 400,
	    success: false,
	    message: "参数格式错误",
	    details: "day参数格式应为YYYY-MM-DD"
	  };
	}
	//日期有效性校验
	const dateObj = new Date(day);
	if (isNaN(dateObj.getTime())) {
	    return {
	        success: false,
	        code: 400,
	        message: "提供的日期无效"
	    };
	}
	
	// 4. 时间段格式校验
	const timeSlotRegex = /^([01]?[0-9]|2[0-3]):00-([01]?[0-9]|2[0-3]):50$/;
	if (!timeSlotRegex.test(freeSlot)) {
	  return {
	    code: 400,
	    success: false,
	    message: "时间段格式错误",
	    details: "必须为整点开始、50分钟结束的区间，例如: 09:00-09:50"
	  };
	}
	
	// 解析时间段
	const [startTime, endTime] = freeSlot.split('-');
	const [startHour, startMinute] = startTime.split(':').map(Number);
	const [endHour, endMinute] = endTime.split(':').map(Number);
	
	// 检查时间跨度是否为50分钟
	const startTotalMinutes = startHour * 60 + startMinute;
	const endTotalMinutes = endHour * 60 + endMinute;
	
	if (endTotalMinutes - startTotalMinutes !== 50) {
	  return {
	    code: 400,
	    success: false,
	    message: "时间段格式错误",
	    details: "必须为整点开始、50分钟结束的区间，例如: 09:00-09:50"
	  };
	}
	
    try {
        const collection = db.collection("consultant_schedule");
        
        // 查找当天的空闲时段记录
        let existingRecord = await collection.where({ user: uid, day }).get();

        if (existingRecord.data.length > 0) {
            // 记录已存在，更新 freeSlots
            await collection.doc(existingRecord.data[0]._id).update({
                freeSlots: db.command.addToSet(freeSlot)
            });
        } else {
            // 记录不存在，创建新记录
            await collection.add({
                user: uid,  // 这里修改为 user
				isShow: false,  // 创建时 isShow 设为 false
                day,
                freeSlots: [freeSlot],
                createdAt: new Date()
            });
        }

        return { success: true, message: "空闲时段已更新" };
    } catch (error) {
        console.error("数据库操作失败:", error);
        return { success: false, message: "数据库错误" };
    }
};
